package com.example.word.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.word.dto.TempSelectDTO;
import com.example.word.dto.TemplateBackDTO;
import com.example.word.dto.TemplateDTO;
import com.example.word.enums.FilePathEnum;
import com.example.word.exception.BizException;
import com.example.word.mapper.CompRecordMapper;
import com.example.word.pojo.CompRecord;
import com.example.word.pojo.Template;
import com.example.word.service.RedisService;
import com.example.word.service.TemplateService;
import com.example.word.mapper.TemplateMapper;
import com.example.word.strategy.context.UploadStrategyContext;
import com.example.word.util.*;
import com.example.word.vo.ConditionVO;
import com.example.word.vo.PageResult;
import com.example.word.vo.TemplateVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;


import static com.example.word.constant.CommonConst.TRUE;
import static com.example.word.constant.RedisPrefixConst.TEMPLATE_COMP_COUNT;


/**
 *
 */
@Service
public class TemplateServiceImpl extends ServiceImpl<TemplateMapper, Template>
    implements TemplateService{

    @Autowired
    private TemplateMapper templateMapper;
    @Autowired
    private UploadStrategyContext uploadStrategyContext;
    @Autowired
    private CompRecordMapper compRecordMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ExecutorService executorService;

    @Override
    public boolean validateFile(String eName,String path) {
        Integer tId = UserUtils.getLoginUser().getUserInfoId();

        List<Template> templateList = templateMapper.selectList(new LambdaQueryWrapper<Template>()
                .eq(Template::getTId, tId));
        templateList.forEach(template -> {
            if(template.getEName().equals(eName)){
                throw new BizException("请换一个别名");
            }
        });

        //获取模板属性
        TemplateDTO templateDTO = AttributesUtils.getAttributes(path);
        templateDTO.setPath(path);
        templateDTO.setTId(tId);
        templateDTO.setName(path.split("/")[path.split("/").length - 1]);
        System.out.println(path.split("/")[path.split("/").length - 1]);
        templateDTO.setEName(eName);
        templateDTO.setStatus(TRUE);
        Template template = BeanCopyUtils.copyObject(templateDTO, Template.class);
        templateMapper.insert(template);
        return true;
    }

    @Override
    public PageResult<TemplateBackDTO> listTemplateBacks(ConditionVO condition) {
        //查询模板总量
        Integer count = templateMapper.selectCount(null);
        if (count == 0) {
            return new PageResult<>();
        }
        // 查询后台模板
        List<TemplateBackDTO> TemplateBackDTOList = templateMapper.listTemplateBacks(PageUtils.getLimitCurrent(), PageUtils.getSize(), condition);
        return new PageResult<>(TemplateBackDTOList,count);

    }

    @Override
    public void uploadTemplate(String eName, MultipartFile file) throws IOException {
        //获取模板路径
        String path = uploadStrategyContext.executeUploadStrategy(file, FilePathEnum.WD.getPath());
//        Integer tId = UserUtils.getLoginUser().getUserInfoId();
//
//        List<Template> templateList = templateMapper.selectList(new LambdaQueryWrapper<Template>()
//                .eq(Template::getTId, tId));
//        templateList.forEach(template -> {
//            if(template.getEName().equals(eName)){
//                throw new BizException("请换一个别名");
//            }
//        });

        //获取模板属性
        TemplateDTO templateDTO = AttributesUtils.getAttributes(path);
        templateDTO.setPath(path);
        templateDTO.setTId(1);
        templateDTO.setName(this.getFileName(file.getOriginalFilename()));
        templateDTO.setEName(eName);
        templateDTO.setStatus(TRUE);
        Template template = BeanCopyUtils.copyObject(templateDTO, Template.class);
        templateMapper.insert(template);
    }

    @Override
    public String compareByUpload(HttpServletRequest request, HttpSession session) {
        String ipAddress = IpUtils.getIpAddress(request);
        String filePath = redisService.get(ipAddress + "filePath").toString();
        String templatePath = redisService.get(ipAddress + "templatePath").toString();
        TemplateDTO templateDTO = AttributesUtils.getAttributes(templatePath);
        String downloadPath = FileUtils.FileCompare(filePath, templateDTO);
        String fileName = this.getUpFileName(new File(filePath).getName());
        String templateName = this.getUpFileName(new File(templatePath).getName());

        String resultName = this.getUpFileName(new File(downloadPath).getName());
        if(templateDTO.getTId() != null){
            CompRecord compRecord = CompRecord.builder()
                    .tId(0)
                    .fileName(fileName)
                    .templateId(0)
                    .uId(UserUtils.getLoginUser().getUserInfoId())
                    .templateName(templateName)
                    .resultName(resultName)
                    .resultPath(downloadPath).build();
            Runnable insertIntoDb = () -> compRecordMapper.insert(compRecord);
            executorService.execute(insertIntoDb);
        }

        //compRecordMapper.insert(compRecord);
        // 提交Runnable到线程池，异步执行

        return downloadPath;
    }

    @Override
    public String compareBySelect(HttpServletRequest request, Integer id) {
        String ipAddress = IpUtils.getIpAddress(request);
        String filePath = redisService.get(ipAddress + "filePath").toString();
        Template template = templateMapper.selectById(id);
        String fileName = this.getUpFileName(new File(filePath).getName());
        String templateName = template.getName();
        String downloadPath = FileUtils.FileCompare(filePath, BeanCopyUtils.copyObject(template, TemplateDTO.class));
        String resultName = this.getUpFileName(new File(downloadPath).getName());
        redisService.zIncr(TEMPLATE_COMP_COUNT, template.getId(), 1D);
        CompRecord compRecord = CompRecord.builder()
                .tId(template.getTId())
                .fileName(fileName)
                .templateId(id)
                .uId(UserUtils.getLoginUser().getUserInfoId())
                .templateName(templateName)
                .resultName(resultName)
                .resultPath(downloadPath).build();
        Runnable insertIntoDb = () -> compRecordMapper.insert(compRecord);
        //compRecordMapper.insert(compRecord);
        // 提交Runnable到线程池，异步执行
        executorService.execute(insertIntoDb);

        return downloadPath;
    }


//    @Override
//    public String compareBySelect(HttpServletRequest request, Integer id) {
//        String ipAddress = IpUtils.getIpAddress(request);
//        String filePath = redisService.get(ipAddress + "filePath").toString();
//        Template template = templateMapper.selectById(id);
//        String fileName = this.getUpFileName(new File(filePath).getName());
//        String templateName = template.getName();
//        String downloadPath = FileUtils.FileCompare(filePath, BeanCopyUtils.copyObject(template, TemplateDTO.class));
//        String resultName = this.getUpFileName(new File(downloadPath).getName());
//        CompRecord compRecord = CompRecord.builder()
//                .tId(template.getTId())
//                .fileName(fileName)
//                .templateId(id)
//                .uId(UserUtils.getLoginUser().getUserInfoId())
//                .templateName(templateName)
//                .resultName(resultName)
//                .resultPath(downloadPath).build();
//        compRecordMapper.insert(compRecord);
//        return downloadPath;
//    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdateTemplate(TemplateVO templateVO) {
        if(templateVO.getId() == null){
            Integer count = templateMapper.selectCount(new LambdaQueryWrapper<Template>()
                    .eq(Template::getEName, templateVO.getEname())
                    .eq(Template::getTId, templateVO.getTid()));
            if(count > 0){
                throw new BizException("请换一个别名");
            }
        }
        Template template = BeanCopyUtils.copyObject(templateVO, Template.class);
        template.setTId(templateVO.getTid());
        template.setPath("word://template");
        template.setName(templateVO.getTid() +"自定义模板");
        template.setEName(templateVO.getEname());
        this.saveOrUpdate(template);
    }

//    @Override
//    public PageResult<TemplateDTO> listTemplates() {
//        Integer count = templateMapper.selectCount(new LambdaQueryWrapper<Template>()
//                .eq(Template::getStatus, 1));
//        if (count == 0) {
//            return new PageResult<>();
//        }
//        List<Template> templates = templateMapper.selectList(new LambdaQueryWrapper<Template>()
//        .eq(Template::getStatus, 1));
//
//        return new PageResult<>( BeanCopyUtils.copyList(templates, TemplateDTO.class), count);
//    }

    @Override
    public PageResult<TemplateDTO> listTemplatesById(ConditionVO condition) {
        Integer tId = UserUtils.getLoginUser().getUserInfoId();
        Integer count = templateMapper.selectCount(new LambdaQueryWrapper<Template>()
        .eq(Template::getTId, tId));
        if (count == 0) {
            return new PageResult<>();
        }
        // 查询后台模板
        List<TemplateDTO> TemplateDTOList = templateMapper.listTemplatesById(tId,PageUtils.getLimitCurrent(), PageUtils.getSize(), condition);
        return new PageResult<>(TemplateDTOList, count);
    }

    @Override
    public PageResult<TempSelectDTO> listTemplateSelects(ConditionVO condition) {
        //查询模板总量
        Integer count = templateMapper.selectCount(null);
        if (count == 0) {
            return new PageResult<>();
        }
        List<TempSelectDTO> tempSelectDTOS = templateMapper.listTemplateSelects(PageUtils.getLimitCurrent(), PageUtils.getSize(), condition);

        return new PageResult<>(tempSelectDTOS, count);
    }

    /**
     * 获取保存过文档的名称 去掉前缀跟后缀
     * @param fileName
     * @return
     */
    public String getUpFileName(String fileName){
        int start = fileName.indexOf("_") + 1; // 获取下划线后第一个字符的索引
        int end = fileName.indexOf("."); // 获取文件扩展名前的字符的索引
        String result = fileName.substring(start, end);
        return result;
    }
    /**
     * 获取文档的名称 去掉后缀
     * @param fileName
     * @return
     */
    public String getFileName(String fileName){
        int end = fileName.indexOf("."); // 获取文件扩展名前的字符的索引
        String result = fileName.substring(0, end);
        return result;
    }

    public void incrTempCompCount(int id,String name){


    }
}




